import router from '../router/index'
import {config} from "./config"

interface ApiResponse<T> {
    data: T;
    code: number;
    msg: string;
}

// 封装通用的 fetch 函数
async function apiFetch<T>(url: string, options?: RequestInit): Promise<ApiResponse<T>> {
    const fullUrl: string = `${config.baseUrl}${url}`
    // 创建配置对象，但不立即设置 headers
    const fetchOptions: RequestInit = {
        credentials: 'include',
        ...options,
    };
    
    // 只有当请求体不是 FormData 时才设置 JSON Content-Type
    if (!(fetchOptions.body instanceof FormData)) {
        fetchOptions.headers = {
            'Content-Type': 'application/json;charset=UTF-8',
            ...options?.headers,
        };
    } else {
        // 对于 FormData，使用原始的 headers 或者空对象
        fetchOptions.headers = options?.headers || {};
    }
    const response = await fetch(fullUrl, fetchOptions);
    if (response.status === 401) {
        router.push({
        path: '/',
        query: { redirect: router.currentRoute.value.fullPath }
      })
      return
    }
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    const apiResponse: ApiResponse<T> = await response.json();

    // 根据业务逻辑判断请求是否成功
    if (apiResponse.code !== 200) {
        throw new Error(apiResponse.msg);
    }

    return apiResponse;
}


export const storeFile =(file:File)=>{
  const formData = new FormData();
  formData.append('file', file);
  return apiFetch<string>(`/store-file`, {
    method: 'POST',
    body: formData,
  })
}

interface User {
    id?: number;
    account?: string;
    nickname?: string;
    avatar?: string;
    password?: string;
}
export const editUser =(user:User)=>{
  return apiFetch<number>(`/edit-user`, {
    method: 'POST',
    body: JSON.stringify(user)
  })
}

export const addUser =(user:User)=>{
  return apiFetch<number>(`/add-user`, {
    method: 'POST',
    body: JSON.stringify(user)
  })
}

export const listUser=()=>{
  return apiFetch<User[]>(`/user-list`, {
    method: 'GET',
  })
}

export const deleteUser=(userAccounts:string[])=>{
  return apiFetch<string>(`/delete-users`, {
    method: 'POST',
    body: JSON.stringify({userAccounts})
  })
}

interface Document {
    fileName?: string;
    uploadTime?: string;
    title?: string;
    userId?: string;
}
interface FileQuery{
  keyword?:string
}

export const listFile=(fileQuery:FileQuery)=>{
  return apiFetch<Document[]>(`/list-file`, {
    method: 'POST',
    body: JSON.stringify(fileQuery)
  })
}


export const uploadDocx=(docx:File)=>{
  const formData = new FormData();
  formData.append('docx', docx);
  return apiFetch<string>(`/upload-doc`, {
    method: 'POST',
    body: formData,
  })
}


export const deleteDocs=(fileIds:string[])=>{
  return apiFetch<string>(`/delete-docs`, {
    method: 'POST',
    body: JSON.stringify(fileIds)
  })
}